<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2021/3/31
 * Time: 12:37
 */

namespace common\wodrow\wyiibackup;


use wodrow\yii2wtools\tools\FileHelper;
use yii\base\Component;
use yii\base\Exception;

class DbJobBackup extends Component
{
    const DB_TYPE_MYSQL = "mysql";

    public $name;
    public $dbBackupWaitUploadRoot = "@uploads_root";
    public $dbBackupKeepRoot = "@dbbackup_root/db";
    public $keep = 10;
    public $dbType = self::DB_TYPE_MYSQL;
    public $dbHost = "127.0.0.1";
    public $dbPort = "3306";
    public $dbUser = "root";
    public $dbPass = "root";
    public $dbNames;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        if (substr($this->dbBackupWaitUploadRoot, 0, 1) === "@"){
            $this->dbBackupWaitUploadRoot = \Yii::getAlias("{$this->dbBackupWaitUploadRoot}/dbs/{$this->name}");
        }
        if (substr($this->dbBackupKeepRoot, 0, 1) === "@"){
            $this->dbBackupKeepRoot = \Yii::getAlias("{$this->dbBackupKeepRoot}/{$this->name}");
        }
    }

    /**
     * @param string $params
     * @throws
     */
    public function dbBackupKeep($params = "")
    {
        if ($this->keep > 0){
            $backDir = $this->dbBackupKeepRoot;
            $backTDir = $backDir. DIRECTORY_SEPARATOR . YII_BT_TIME;
            if (!is_dir($backTDir))FileHelper::createDirectory($backTDir);
            $this->dbBackup($backTDir, $params);
            $files = FileHelper::listDir($backDir, false);
            $_files = [];
            foreach ($files as $k => $v){
                $t = basename($v);
                if (!\common\components\Tools::isTimestamp($t)){
                    FileHelper::removeDirectory($v);
                }else{
                    $_files[$t] = $v;
                }
            }
            krsort($_files);
            $bl = array_slice($_files, 0, $this->keep);
            $rms = array_diff($_files, $bl);
            foreach ($rms as $k => $v) {
                FileHelper::removeDirectory($v);
            }
        }
    }

    /**
     * @param string $params
     * @throws
     */
    public function dbBackupWaitUpload($params = "")
    {
        $this->dbBackup($this->dbBackupWaitUploadRoot, $params);
    }

    /**
     * @param string $backupDir
     * @param string $params
     * @throws
     */
    public function dbBackup($backupDir, $params = "")
    {
        if (!is_dir($backupDir)){
            FileHelper::createDirectory($backupDir);
        }
        $exec_str = "";
        switch ($this->dbType){
            case self::DB_TYPE_MYSQL:
                $exec_str .= "mysqldump -u{$this->dbUser} ";
                if (PHP_OS === "WINNT"){
                    $exec_str .= "-p{$this->dbPass} ";
                }else{
                    $exec_str .= "-p'{$this->dbPass}' ";
                }
                $exec_str .= "-h{$this->dbHost} ";
                $exec_str .= "-P{$this->dbPort} ";
                $exec_str .= "{$params} ";
                foreach ($this->dbNames as $k => $v) {
                    $exec = "{$exec_str}{$v}>{$backupDir}/{$v}.sql";
                    exec($exec);
                }
                break;
            default:
                throw new Exception("没有找到数据库类型备份工具:{$this->dbType}");
                break;
        }
    }
}